Passed
Push — master ( 6f8171...7c2bcd )
by
unknown
48s
created

CreateWorkEnvironmentAPI.WorkplacePhotoUploader   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 1
rs 10
1
var CreateWorkEnvironmentAPI = {};
2
3
CreateWorkEnvironmentAPI.workplacePhotoUploaders = [];
4
5
CreateWorkEnvironmentAPI.photoNameToCaptionFormId = {'workplace_photo_1': 'workplace_photo_caption_1',
6
    'workplace_photo_2': 'workplace_photo_caption_2',
7
    'workplace_photo_3': 'workplace_photo_caption_3'};
8
9
CreateWorkEnvironmentAPI.defaultWorkplacePhoto = '/images/user.png';
10
11
/**
12
 * 
13
 * @param {string} photo_name
14
 * @param {string} description
15
 * @return {CreateWorkEnvironment.WorkplacePhotoCaption}
16
 */
17
CreateWorkEnvironmentAPI.WorkplacePhotoCaption = function (photo_name, description) {
18
    this.photo_name = photo_name;
19
    this.description = description;
20
};
21
22
/**
23
 * 
24
 * @param {string} remote_allowed
25
 * @param {string} telework_allowed
26
 * @param {string} flexible_allowed
27
 * @param {CreateWorkEnvironment.WorkplacePhotoCaption[]} workplace_photo_captions
28
 * @return {CreateWorkEnvironment.WorkEnvironment}
29
 */
30
CreateWorkEnvironmentAPI.WorkEnvironment = function (remote_allowed, telework_allowed,
31
        flexible_allowed, workplace_photo_captions) {
32
    this.remote_allowed = remote_allowed;
33
    this.telework_allowed = telework_allowed;
34
    this.flexible_allowed = flexible_allowed;
35
    this.workplace_photo_captions = workplace_photo_captions;
36
};
37
38
CreateWorkEnvironmentAPI.localizeCreateWorkEnvironment = function () {
39
    if (siteContent) {
0 ignored issues
show
Best Practice introduced by
If you intend to check if the variable siteContent is declared in the current environment, consider using typeof siteContent === "undefined" instead. This is safe if the variable is not actually declared.
Loading history...
40
        try {
41
            document.getElementById('remoteWork_label').innerHTML = siteContent.remoteLocationAllowed;
42
            document.getElementById('remoteWork_option0_label').innerHTML = SliderAPI.getYesNoSliderLabel("option0");
0 ignored issues
show
Bug introduced by
The variable SliderAPI seems to be never declared. If this is a global, consider adding a /** global: SliderAPI */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
43
            document.getElementById('remoteWork_option1_label').innerHTML = SliderAPI.getYesNoSliderLabel("option1");
44
45
            document.getElementById('telework_label').innerHTML = siteContent.teleworkAllowed;
46
            document.getElementById('telework_option0_label').innerHTML = SliderAPI.getFrequencySliderLabel("option0");
47
            document.getElementById('telework_option1_label').innerHTML = SliderAPI.getFrequencySliderLabel("option1");
48
            document.getElementById('telework_option2_label').innerHTML = SliderAPI.getFrequencySliderLabel("option2");
49
            document.getElementById('telework_option3_label').innerHTML = SliderAPI.getFrequencySliderLabel("option3");
50
            document.getElementById('telework_option4_label').innerHTML = SliderAPI.getFrequencySliderLabel("option4");
51
52
            document.getElementById('flexHours_label').innerHTML = siteContent.flexHoursAllowed;
53
            document.getElementById('flexHours_option0_label').innerHTML = SliderAPI.getFrequencySliderLabel("option0");
54
            document.getElementById('flexHours_option1_label').innerHTML = SliderAPI.getFrequencySliderLabel("option1");
55
            document.getElementById('flexHours_option2_label').innerHTML = SliderAPI.getFrequencySliderLabel("option2");
56
            document.getElementById('flexHours_option3_label').innerHTML = SliderAPI.getFrequencySliderLabel("option3");
57
            document.getElementById('flexHours_option4_label').innerHTML = SliderAPI.getFrequencySliderLabel("option4");
58
59
            document.getElementById('physicalEnvironment_title').innerHTML = siteContent.physicalEnvironment;
60
        } catch (e) {
61
            (console.error || console.log).call(console, e.stack || e);
62
        }
63
    }
64
};
65
66
CreateWorkEnvironmentAPI.parseWorkEnvironmentResponse = function (response) {
67
    var json = JSON.parse(response);
68
    var workEnvironment = new CreateWorkEnvironmentAPI.WorkEnvironment(
69
            json.basic_work_environment.remote_allowed,
70
            json.basic_work_environment.telework_allowed,
71
            json.basic_work_environment.flexible_allowed,
72
            []
73
            );
74
    var captions = json.workplace_photo_captions;
75
    for (var i = 0; i < captions.length; i++) {
76
        var caption = captions[i];
77
        var workplacePhotoCaption = new CreateWorkEnvironmentAPI.WorkplacePhotoCaption(
78
                caption.photo_name,
79
                caption.description
80
                );
81
        workEnvironment.workplace_photo_captions.push(workplacePhotoCaption);
82
    }
83
    return workEnvironment;
84
};
85
86
CreateWorkEnvironmentAPI.initializeWorkEnvironmentForm = function (managerProfileId) {
87
    //Fill previous form fields
88
    DataAPI.getWorkplaceEnvironment(managerProfileId, function (response) {
0 ignored issues
show
Bug introduced by
The variable DataAPI seems to be never declared. If this is a global, consider adding a /** global: DataAPI */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
89
        var workEnv = CreateWorkEnvironmentAPI.parseWorkEnvironmentResponse(response);
90
        CreateWorkEnvironmentAPI.populateWorkEnvironmentForm(workEnv);
91
    })
0 ignored issues
show
Coding Style introduced by
There should be a semicolon.

Requirement of semicolons purely is a coding style issue since JavaScript has specific rules about semicolons which are followed by all browsers.

Further Readings:

Loading history...
92
93
    //Show preivious workplace photos
94
    CreateWorkEnvironmentAPI.refreshWorkplacePhoto(managerProfileId, 'workplace_photo_1', 'workEnvironment_photo_1');
95
    CreateWorkEnvironmentAPI.refreshWorkplacePhoto(managerProfileId, 'workplace_photo_2', 'workEnvironment_photo_2');
96
    CreateWorkEnvironmentAPI.refreshWorkplacePhoto(managerProfileId, 'workplace_photo_3', 'workEnvironment_photo_3');
97
98
    //Set up photo uploaders
99
    CreateWorkEnvironmentAPI.workplacePhotoUploaders = [];
100
    var uploader1 = CreateWorkEnvironmentAPI.makeWorkplacePhotoUploader(managerProfileId, 'workplace_photo_1',
101
            'workplace_photo_input_1', null, 'workEnvironment_photo_1');
102
    var uploader2 = CreateWorkEnvironmentAPI.makeWorkplacePhotoUploader(managerProfileId, 'workplace_photo_2',
103
            'workplace_photo_input_2', null, 'workEnvironment_photo_2');
104
    var uploader3 = CreateWorkEnvironmentAPI.makeWorkplacePhotoUploader(managerProfileId, 'workplace_photo_3',
105
            'workplace_photo_input_3', null, 'workEnvironment_photo_3');
106
107
    CreateWorkEnvironmentAPI.workplacePhotoUploaders.push(uploader1, uploader2, uploader3);
108
};
109
110
/**
111
 * 
112
 * @param {CreateWorkEnvironment.WorkEnvironment} workEnvironment
113
 * @return {undefined}
114
 */
115
CreateWorkEnvironmentAPI.populateWorkEnvironmentForm = function (workEnvironment) {
116
117
118
119
120
    SliderAPI.selectOptionByValue("createEditProfile_remoteWork", workEnvironment.remote_allowed, "remoteWork");
0 ignored issues
show
Bug introduced by
The variable SliderAPI seems to be never declared. If this is a global, consider adding a /** global: SliderAPI */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
121
    SliderAPI.selectOptionByValue("createEditProfile_telework", workEnvironment.telework_allowed, "telework");
122
    SliderAPI.selectOptionByValue("createEditProfile_flexHours", workEnvironment.flexible_allowed, "flexHours");
123
    var captions = workEnvironment.workplace_photo_captions;
124
    for (var i = 0; i < captions.length; i++) {
125
        var caption = captions[i];
126
        var captionFormElementId = CreateWorkEnvironmentAPI.photoNameToCaptionFormId[caption.photo_name];
127
        if (captionFormElementId) {
128
            document.getElementById(captionFormElementId).value = caption.description;
129
        }
130
    }
131
};
132
133
CreateWorkEnvironmentAPI.refreshWorkplacePhoto = function (managerProfileId, photoName, previewImageElementId) {
134
    var photoUrl = DataAPI.baseURL + '/getWorkplacePhotoByManagerProfileAndName/' + managerProfileId + '/' + photoName;
0 ignored issues
show
Bug introduced by
The variable DataAPI seems to be never declared. If this is a global, consider adding a /** global: DataAPI */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
135
    DataAPI.sendRequest(photoUrl, 'GET', {"Accept":"image/*"}, null, function(request) {
136
        var img = document.getElementById(previewImageElementId);
137
        if (request.status == 200 && request.responseURL) {
138
            img.src = request.responseURL;
139
        } else {
140
            img.src = CreateWorkEnvironmentAPI.defaultWorkplacePhoto;
141
        }
142
    });
143
};
144
145
CreateWorkEnvironmentAPI.saveWorkEnvironment = function (managerProfileId) {
146
    var defaultOption = "option0";
147
    var remoteAllowedSelected = document.querySelector('input[name="createEditProfile_remoteWork"]:checked');
148
    if (remoteAllowedSelected === null) {
149
        var remoteAllowed = defaultOption;
150
    } else {
151
        var remoteAllowed = remoteAllowedSelected.value;
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable remoteAllowed already seems to be declared on line 149. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
Bug introduced by
It seems like remoteAllowed was already defined.
Loading history...
152
    }
153
154
    var teleworkAllowedSelected = document.querySelector('input[name="createEditProfile_telework"]:checked');
155
    if (teleworkAllowedSelected === null) {
156
        var teleworkAllowed = defaultOption;
157
    } else {
158
        var teleworkAllowed = teleworkAllowedSelected.value;
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable teleworkAllowed already seems to be declared on line 156. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
Bug introduced by
It seems like teleworkAllowed was already defined.
Loading history...
159
    }
160
161
    var flexibleAllowedSelected = document.querySelector('input[name="createEditProfile_flexHours"]:checked');
162
    if (flexibleAllowedSelected === null) {
163
        var flexibleAllowed = defaultOption;
164
    } else {
165
        var flexibleAllowed = flexibleAllowedSelected.value;
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable flexibleAllowed already seems to be declared on line 163. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
Bug introduced by
It seems like flexibleAllowed was already defined.
Loading history...
166
    }
167
168
    var workEnvironment = new CreateWorkEnvironmentAPI.WorkEnvironment(remoteAllowed, teleworkAllowed, flexibleAllowed, []);
0 ignored issues
show
Bug introduced by
The variable remoteAllowed seems to be used out of scope.

This error can usually be fixed by declaring the variable in the scope where it is used:

function someFunction() {
    (function() {
        var i = 0;
    })();

    // i is not defined.
    alert(i);
}

// This can be fixed by moving the var statement to the outer scope.

function someFunction() {
    var i;
    (function() {
        i = 1;
    })();

    alert(i);
};
Loading history...
Bug introduced by
The variable teleworkAllowed seems to be used out of scope.

This error can usually be fixed by declaring the variable in the scope where it is used:

function someFunction() {
    (function() {
        var i = 0;
    })();

    // i is not defined.
    alert(i);
}

// This can be fixed by moving the var statement to the outer scope.

function someFunction() {
    var i;
    (function() {
        i = 1;
    })();

    alert(i);
};
Loading history...
Bug introduced by
The variable flexibleAllowed seems to be used out of scope.

This error can usually be fixed by declaring the variable in the scope where it is used:

function someFunction() {
    (function() {
        var i = 0;
    })();

    // i is not defined.
    alert(i);
}

// This can be fixed by moving the var statement to the outer scope.

function someFunction() {
    var i;
    (function() {
        i = 1;
    })();

    alert(i);
};
Loading history...
169
170
    for (var name in CreateWorkEnvironmentAPI.photoNameToCaptionFormId) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
171
        var descriptionFormId = CreateWorkEnvironmentAPI.photoNameToCaptionFormId[name];
172
        var description = document.getElementById(descriptionFormId).value;
173
        var photoCaption = new CreateWorkEnvironmentAPI.WorkplacePhotoCaption(name, description);
174
        workEnvironment.workplace_photo_captions.push(photoCaption);
175
    }
176
177
    DataAPI.submitWorkplaceEnvironment(managerProfileId, workEnvironment, function () {}); //TODO add response callback
0 ignored issues
show
Bug introduced by
The variable DataAPI seems to be never declared. If this is a global, consider adding a /** global: DataAPI */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
178
179
    for (var i = 0; i < CreateWorkEnvironmentAPI.workplacePhotoUploaders.length; i++) {
180
        CreateWorkEnvironmentAPI.workplacePhotoUploaders[i].uploadPhoto();
181
    }
182
}
0 ignored issues
show
Coding Style introduced by
There should be a semicolon.

Requirement of semicolons purely is a coding style issue since JavaScript has specific rules about semicolons which are followed by all browsers.

Further Readings:

Loading history...
183
184
CreateWorkEnvironmentAPI.makeWorkplacePhotoUploader = function (managerProfileId, photoName, inputId, dropzoneId, previewId) {
185
    var photoInput = document.getElementById(inputId);
186
    if (dropzoneId) {
187
        var photoDropzone = document.getElementById(dropzoneId);
188
    } else {
189
        var photoDropzone = null;
0 ignored issues
show
Comprehensibility Naming Best Practice introduced by
The variable photoDropzone already seems to be declared on line 187. Consider using another variable name or omitting the var keyword.

This check looks for variables that are declared in multiple lines. There may be several reasons for this.

In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs.

If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared.

Loading history...
Bug introduced by
It seems like photoDropzone was already defined.
Loading history...
190
    }
191
    var photoPreview = document.getElementById(previewId);
192
    var uploadUrl = DataAPI.baseURL + "/putWorkplacePhotoByManagerProfileAndName/" + managerProfileId + '/' + photoName;
0 ignored issues
show
Bug introduced by
The variable DataAPI seems to be never declared. If this is a global, consider adding a /** global: DataAPI */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
193
194
    var uploader = new CreateWorkEnvironmentAPI.WorkplacePhotoUploader(
195
            photoInput, photoDropzone, photoPreview,
0 ignored issues
show
Bug introduced by
The variable photoDropzone seems to be used out of scope.

This error can usually be fixed by declaring the variable in the scope where it is used:

function someFunction() {
    (function() {
        var i = 0;
    })();

    // i is not defined.
    alert(i);
}

// This can be fixed by moving the var statement to the outer scope.

function someFunction() {
    var i;
    (function() {
        i = 1;
    })();

    alert(i);
};
Loading history...
196
            uploadUrl,
197
            function (request) {
0 ignored issues
show
Unused Code introduced by
The parameter request is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
198
                //TODO: handle upload response
199
200
            });
201
202
    return uploader;
203
};
204
205
CreateWorkEnvironmentAPI.WorkplacePhotoUploader = function (
206
        inputField, dropZone, previewImgElement,
207
        uploadUrl,
208
        onUploadComplete) {
209
210
    this.inputField = inputField;
211
    this.dropZone = dropZone;
212
    this.previewImgElement = previewImgElement;
213
    this.uploadUrl = uploadUrl;
214
    this.onUploadComplete = onUploadComplete;
215
216
    this.photo = null;
217
    this.max_filesize = 2048576;
218
    this.defaultPhotoSrc = CreateWorkEnvironmentAPI.defaultWorkplacePhoto;
219
220
    var self = this;
221
222
    self.init = function () {
223
        self.inputField.onchange = self.addFiles;
224
        if (self.dropZone)
225
            self.initializeDropzone();
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
226
    };
227
228
    //clone dropZone to remove existing event listeners
229
    self.initializeDropzone = function () {
230
        var clone = self.dropZone.cloneNode();
231
        while (self.dropZone.firstChild) {
232
            clone.appendChild(self.dropZone.lastChild);
233
        }
234
        self.dropZone.parentNode.replaceChild(clone, self.dropZone);
235
        self.dropZone = clone;
236
237
        self.dropZone.addEventListener("dragenter", self.stopProp, false);
238
        self.dropZone.addEventListener("dragleave", self.dragExit, false);
239
        self.dropZone.addEventListener("dragover", self.dragOver, false);
240
        self.dropZone.addEventListener("drop", self.processDroppedFiles, false);
241
    };
242
243
    self.setFiles = function (files) {
244
        self.processNewFiles(files);
245
    };
246
247
    self.addFiles = function () {
248
        self.processNewFiles(this.files);
249
    };
250
251
    self.processDroppedFiles = function (ev) {
252
        self.stopProp(ev);
253
        var files = ev.dataTransfer.files;
254
        self.processNewFiles(files);
255
    };
256
257
    self.dragOver = function (ev) {
258
        self.stopProp(ev);
259
        self.dropZone.classList.remove("fileDropzoneNormal");
260
        self.dropZone.classList.add("fileDropzoneHighlight");
261
        //this.style["backgroundColor"] = "#F0FCF0";
262
        //this.style["borderColor"] = "#3DD13F";
263
        //this.style["color"] = "#3DD13F";
264
    };
265
266
    self.dragExit = function (ev) {
267
        self.stopProp(ev);
268
        self.dropZone.classList.remove("fileDropzoneHighlight");
269
        self.dropZone.classList.add("fileDropzoneNormal");
270
        //dropZone.style["backgroundColor"] = "#FEFEFE";
271
        //dropZone.style["borderColor"] = "#CCC";
272
        //dropZone.style["color"] = "#CCC";
273
    };
274
275
    self.stopProp = function (ev) {
276
        ev.stopPropagation();
277
        ev.preventDefault();
278
    };
279
280
    self.clearUpload = function () {
281
        //Clear upload 
282
        self.photo = null;
283
284
        //Clear preview
285
        self.previewImgElement.src = self.defaultPhotoSrc;
286
287
        //Clear input button value
288
        self.inputField.value = null;
289
    };
290
291
    self.processNewFiles = function (files) {
292
        var file = files[0];
293
        if (file.type.match('image.*')) {
294
            self.clearUpload();
295
            var fr = new FileReader();
0 ignored issues
show
Bug introduced by
The variable FileReader seems to be never declared. If this is a global, consider adding a /** global: FileReader */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
296
            fr.file = file;
297
            fr.onloadend = function (ev) {
298
299
                if (ev.target.file.size < self.max_filesize) {
300
                    self.photo = ev.target.file;
301
                    self.previewImgElement.src = ev.target.result;
302
                } else {
0 ignored issues
show
Comprehensibility Documentation Best Practice introduced by
This code block is empty. Consider removing it or adding a comment to explain.
Loading history...
303
                    //TODO: indicate overlarge file
304
                }
305
            };
306
            fr.readAsDataURL(fr.file);
307
        } else {
0 ignored issues
show
Comprehensibility Documentation Best Practice introduced by
This code block is empty. Consider removing it or adding a comment to explain.
Loading history...
308
            //TODO: indicate imporper file type
309
        }
310
    };
311
312
    self.uploadPhoto = function () {
313
        if (self.photo) {
314
            var headers = {"Content-type": self.photo.type, 
315
                "X-File-Name": self.photo.name,
316
                "Accept": "application/json"
317
            }
0 ignored issues
show
Coding Style introduced by
There should be a semicolon.

Requirement of semicolons purely is a coding style issue since JavaScript has specific rules about semicolons which are followed by all browsers.

Further Readings:

Loading history...
318
            DataAPI.sendRequest(self.uploadUrl, "PUT", headers, self.photo, function(request) {
0 ignored issues
show
Bug introduced by
The variable DataAPI seems to be never declared. If this is a global, consider adding a /** global: DataAPI */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
319
                if (self.onUploadComplete) {
320
                    self.onUploadComplete(request);
321
                }
322
            });
323
        }
324
    };
325
326
    self.init(); //call init function at end of constructor
327
};
328
329
330